// pages/cart/confirmorder/confirmorder.js
var api = require('../../../api/api.js')
const pay = require('../../../services/pay.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    settlementGoods: [],
    allGoodsPrices: 0,
    userInfo: wx.getStorageSync("userInfo"),
    wayItems: [{
        name: 'radioLogistic',
        value: '物流'
      },
      {
        name: 'radioEMS',
        value: '快递',
        checked: 'true'
      },
    ],
    // payWays: [{
    //     name: 'weixin',
    //     value: '微信支付',
    //     checked: 'true'
    //   },
    //   {
    //     name: 'yue',
    //     value: '余额支付'
    //   },
    // ],
    way: "radioEMS",
    payWay: "weixin",
    isDisabled: false,
    emsSelect: true,
    weixinSelect: true,
    curAddressData: [],
    logistics: [],
    logisticsmessage: {},
    idArray: "",
    isShowCompany: false,
    hideLogisticsPopup: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function() {

  },

  addAddress: function() {
    wx.navigateTo({
      url: "/pages/address/new-address/new-address"
    })
  },

  selectAddress: function() {
    wx.navigateTo({
      url: "/pages/address/select-address/select-address"
    })
  },

  //选择物流公司
  selectLogistics: function() {
    var that = this;
    that.setData({
      hideLogisticsPopup: false
    })
    wx.showLoading({
      "mask": true,
      title: '加载中...'
    });
    wx.request({
      url: api.LogisticsCompany,
      data: {},
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.error_code == 0) {
          that.setData({
            logistics: res.data.logistics
          })
        }
      }
    })
  },

  selectCompanyTap: function(e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    var logisticsmessage = that.data.logistics[index];
    that.setData({
      logisticsmessage: logisticsmessage,
      hideLogisticsPopup: true,
      isShowCompany: true
    })
  },

  closePopupTap: function() {
    this.setData({
      hideLogisticsPopup: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    that.initShippingAddress();
    that.getCheckoutInfo();
    var userMoney = that.data.userInfo.money;
    var allGoodsPrices = that.data.allGoodsPrices;
    if (parseInt(userMoney) < parseInt(allGoodsPrices)) {
      that.setData({
        isDisabled: true
      })
    }
  },

  initShippingAddress: function() {
    let that = this;
    wx.request({
      url: api.AddressGet,
      data: {},
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function(res) {
        if (res.data.error_code == 0) {
          that.setData({
            curAddressData: res.data.consignees
          })
        }
      }
    })
  },

  //获取产品
  getCheckoutInfo: function() {
    let that = this;
    let settlementGoods = wx.getStorageSync('settlementGoods');
    let idArray = settlementGoods.map(function(e, i) {
      return e.id;
    })

    that.setData({
      settlementGoods: settlementGoods,
      allGoodsPrices: that.getAllGoodsPrices(settlementGoods),
      idArray: JSON.stringify(idArray)
    })
  },

  //计算产品总价
  getAllGoodsPrices: function(settlementGoods) {
    let allGoodsPrices = 0;
    settlementGoods.forEach(function(v) {
      if (v.active === true) {
        allGoodsPrices += v.amount * v.price;
      }
    });

    return allGoodsPrices;
  },

  radioChange: function(e) {
    let that = this;
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    var value = e.detail.value;
    if (value == null || value == "radioEMS") {
      that.setData({
        emsSelect: true,
        way: "radioEMS"
      });
    } else if (value == "radioLogistic") {
      that.setData({
        emsSelect: false,
        way: value
      });
    }
    // that.setData({
    //   way: value
    // });
  },

  radioPayChange: function(e) {
    let that = this;
    var userMoney = that.data.userInfo.money;
    var allGoodsPrices = that.data.allGoodsPrices;
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    var value = e.detail.value;
    if (value == null || value == "weixin") {
      that.setData({
        weixinSelect: true,
        payWay: "weixin"
      });
    } else if (value == "yue") {
      that.setData({
        weixinSelect: false,
        payWay: "yue"
      })
    }
  },

  createOrder: function(e) {
    let that = this;
    var payWay = that.data.payWay;
    var curAddressData = that.data.curAddressData;
    var consignee = "";
    if (curAddressData.length > 0) {
      var consignee = curAddressData[0].id;
    }
    var logisticsmessage = that.data.logisticsmessage;
    var shipping = "";
    var tel = "";
    var address = "";
    if (that.data.way == "radioEMS") {
      if (consignee == 0 || consignee == "" || consignee == null) {
        wx.showToast({
          title: '请选择收货地址',
          image: "/images/icon/error_icon.png"
        });
        return false;
      }
    }
    if (that.data.way == "radioLogistic") {
      if (JSON.stringify(logisticsmessage) == "{}") {
        wx.showToast({
          title: '请选择物流地址',
          image: "/images/icon/error_icon.png"
        });
        return false;
      }
      shipping = logisticsmessage.name;
      tel = logisticsmessage.tel;
      address = logisticsmessage.address;
    }
    var remark = ""; // 备注信息
    if (e) {
      remark = e.detail.value.remark; // 备注信息
    }
    var idArray = that.data.idArray;
    console.log(idArray);
    that.CheckOutCart(consignee, shipping, tel, address, idArray, remark, payWay)
  },

  CheckOutCart: function(consignee, shipping, tel, address, idArray, remark, payWay) {
    let that = this;
    wx.showLoading({
      "mask": true,
      title: '结算中...'
    });
    wx.request({
      url: api.CheckOutCart,
      data: {
        consignee: consignee,
        shipping_name: shipping,
        logistics_tel: tel,
        logistics_address: address,
        cart_good_id: idArray,
        comment: remark,
        client_type: 5
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.error_code === 0) {
          wx.setStorageSync('settlementGoods', []);
          const orderId = res.data.order.id;
          if (payWay == "weixin") {
            pay.payOrder(parseInt(orderId)).then(res => {
              wx.redirectTo({
                url: '/pages/payResult/payResult?status=1&orderId=' + orderId
              });
            }).catch(res => {
              wx.redirectTo({
                url: '/pages/payResult/payResult?status=0&orderId=' + orderId
              });
            });
          }
          if (payWay == "yue") {
            wx.showLoading({
              "mask": true,
              title: '支付中...'
            });
            wx.request({
              url: api.PaymentOrder,
              data: {
                order: orderId,
                code: "balance.pay"
              },
              header: {
                'Content-Type': 'application/json',
                'X-bocang-Authorization': wx.getStorageSync('token')
              },
              method: "POST",
              success: function(res) {
                wx.hideLoading();
                if (res.data.error_code == 0) {
                  wx.showToast({
                    title: "支付成功",
                    icon: 'success'
                  });
                  setTimeout(function () {
                    
                  }, 1000);
                  wx.redirectTo({
                    url: '/pages/order/order/order?status=' + 5,
                  })
                }
              }
            })
          }

        } else {
          var msg = res.data.error_desc;
          wx.showToast({
            title: msg,
            image: '/images/icon/icon_error.png'
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})